package hehe.web;

import hehe.core.base.BaseController;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * web 控制器
 *<B>说明：</B>
 *<pre>
 * 所有http 协议必须基础此控制器
 *</pre>
 *<B>示例：</B>
 *<pre>
 *  略
 *</pre>
 *<B>日志：</B>
 *<pre>
 *  略
 *</pre>
 *<B>注意事项：</B>
 *<pre>
 *  略
 *</pre>
 */
public class WebController extends BaseController
{
    protected HttpServletRequest request;

    public HttpServletRequest getRequest()
    {
        return request;
    }

    /**
     * 控制器初始化方法
     *<B>说明：</B>
     *<pre>
     *  略
     *</pre>
     * @param request 请求
     */
    public void init(HttpServletRequest request)
    {
        this.request = request;
        // post,get 参数注入控制器属性
        this.load();
    }

    /**
     * 从request 获取指定的属性值
     *<B>说明：</B>
     *<pre>
     *  略
     *</pre>
     * @param attributes 属性名称列表['id','age']
     * @return
     */
    protected Map<String,Object> getParameters(List<String> attributes)
    {
        Map<String,Object> parameters = new HashMap<>();
        String name;
        Object value;

        Map<String,Object> requestParameter = this.getRequestParameters();

        for (int i = 0,j = attributes.size();i < j;i++) {
            name = attributes.get(i);
            value = requestParameter.get(name);
            if (value != null) {
                parameters.put(name,value);
            }
        }

        return parameters;
    }

    /**
     * request 参数注入控制器属性
     *<B>说明：</B>
     *<pre>
     *  略
     *</pre>
     */
    protected void load()
    {
        // 读取类的所有属性列表
        List<String> attributesName = this.attributes();

        Map<String,Object> attributes = this.getParameters(attributesName);

        this.setAttrs(this,attributes);
    }

    /**
     * 获取http 所有参数
     *<B>说明：</B>
     *<pre>
     *  基本格式:{"id":"12","name":"admin"}
     *</pre>
     */
    protected Map<String,Object> getRequestParameters()
    {
        Map<String,Object> parameters = new HashMap<>();
        Enumeration<String> attrs = request.getAttributeNames();
        String attrName;
        while (attrs.hasMoreElements()) {
            attrName = attrs.nextElement();
            parameters.put(attrName,request.getAttribute(attrName));
        }

        Enumeration<String> parameterNames = request.getParameterNames();

        String parameterName;
        while (parameterNames.hasMoreElements()) {
            parameterName = parameterNames.nextElement();
            parameters.put(parameterName,request.getParameter(parameterName));
        }

        return parameters;
    }

    public boolean validate()
    {
        return true;
    }

    public Map<String,String> rules()
    {
        return null;
    }
}
